import logging
from binance.um_futures import UMFutures
import pandas as pd
from datetime import datetime
import requests
import time


url = 'https://kyb-api.520iy.com/public/sendWxMsg'


# user_amount  用户总份额 per_portion_val 每份价值
def send_msg(openid,one,two,diff):
    paras = {}
    paras['openid'] = openid
    msg = {}
    paras['msg'] = msg

    msg['type'] = 'income_msg'
    msg['one'] = one
    msg['two'] = two
    msg['diff'] = diff

    msg['time'] = ''
    response = requests.post(url, json=paras)

    # print(paras)

class ShanZhaiFundRateNotice:
    def __init__(self):
        self.um_futures_client = UMFutures()
        self.open_store_condition = 0.0004
        self.notice_history = {}


    def get_now_mill(self):
        # 获取当前时间的datetime对象
        current_datetime = datetime.now()

        # 获取微秒数
        microseconds = current_datetime.timestamp()

        # 转换为毫秒数（注意这会丢失精度）
        milliseconds = microseconds * 1000
        return milliseconds

    def notice(self):
        funding_rate_list = self.find_funding_rate_all()
        for inex,row in funding_rate_list.iterrows():
            funding_rate = row['fr_list']
            if funding_rate >= self.open_store_condition:



                next_funding_time = row['next_funding_time']

                if row['symbol'] in self.notice_history.keys():
                    now_time = self.get_now_mill()
                    last_update_time = self.notice_history[row['symbol']]
                    #10 分钟通知一次
                    if now_time - last_update_time > 1000 * 60 * 10:
                        del self.notice_history[row['symbol']]


                #查询 是否有现货

                if row['symbol'] not in self.notice_history.keys():
                        msg_one = '合约:  {}   '.format(row['symbol'])
                        msg_two = '时间:  {}'.format(datetime.fromtimestamp(next_funding_time/1000))
                        msg_diff = 'V2 fd:  {}'.format(funding_rate)
                        send_msg('ocAr152-22tVKGt2Fp-E9GZ06Oos',one=msg_one,two=msg_two,diff=msg_diff)



                        self.notice_history[row['symbol']] = self.get_now_mill()



                print(row['symbol'] + " : " + str(funding_rate) + " new time :" + str(next_funding_time -self.get_now_mill()))



    def find_funding_rate_all(self):
        funding_rate_list = self.um_futures_client.mark_price()
        fr_data_list = []
        name_list = []
        next_funding_time_list = []

        for fr in funding_rate_list:
            lastFundingRate = fr['lastFundingRate']
            symbol = fr['symbol']
            nextFundingTime = fr['nextFundingTime']

            f_lastFundingRate = float(lastFundingRate)
            if 0 > f_lastFundingRate:
                continue
            name_list.append(symbol)
            fr_data_list.append(f_lastFundingRate)
            next_funding_time_list.append(nextFundingTime)

        data_frame_map = {"symbol": name_list, 'fr_list': fr_data_list,'next_funding_time':next_funding_time_list}
        df = pd.DataFrame(data_frame_map)
        df_sorted_desc = df.sort_values(by='fr_list', ascending=False)
        return df_sorted_desc



if __name__ == '__main__':
    notice = ShanZhaiFundRateNotice()
    while True:
        try:
            notice.notice()
        except Exception as e :
            print(f"Caught an exception: {e}")
        time.sleep(20)
